//
//  TagViewController.m
//  SoundPill
//
//  Created by 宋旭东®Des on 15/1/21.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "TagViewController.h"
#import "JSONKit.h"
#import "AppDelegate.h"
#import "TokenView.h"
#import "AddPersonViewController.h"
#import "UploadWork.h"
#import "JCAlertView.h"
#import "UIImage+UIImageColor.h"
#import "PKYStepper.h"
#import "UIViewExt.h"
#import <CoreLocation/CoreLocation.h>
#define IOS8 [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0
@interface TagViewController ()<UITextFieldDelegate, CLLocationManagerDelegate>
{
    CLLocationManager *_locationManager;
    CLLocationCoordinate2D coordinate;
    CLPlacemark *placemark;
    float price;
}
@property (strong, nonatomic) NSMutableArray *tagArray;
@property (strong, nonatomic) NSArray *tag_imageArray;
@property (strong, nonatomic) NSMutableArray *tag_imageNameArray;
@property (strong, nonatomic) NSMutableArray *tag_imagePathArray;
@property (strong, nonatomic) NSMutableArray *tag_uploadImageArray;
@property (strong, nonatomic) NSMutableArray *tag_textArray;
@property (strong, nonatomic) NSMutableArray *tag_personArray;
@property (strong, nonatomic) NSArray *tag_audioWaveform;
@property (strong, nonatomic) NSString *tag_workTime;
@property (strong, nonatomic) NSString *tags;
@property (strong, nonatomic) NSString *token;
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSMutableDictionary *attachment;
@property (strong, nonatomic) NSMutableDictionary *allInfo;//json
@property (strong, nonatomic) NSNumber *tag_timestamp;
@property (strong, nonatomic) NSNumber *tag_audioSecond;
@property (strong, nonatomic) UITextField *nameText;
@property (strong, nonatomic) UILabel *locationLabel;
//标签
@property (strong, nonatomic) AddTagViewController *addTagController;
@property (strong, nonatomic) UILabel *tagContent;
@property (strong, nonatomic) UIButton *addTag;
@property (assign, nonatomic) BOOL isPrivate;
@property (strong, nonatomic) UISwitch *weixinSwitch;
@property (strong, nonatomic) UISwitch *Private;
//草稿箱
@property (strong, nonatomic) NSString *draftPath;
@property (strong, nonatomic) NSMutableArray *draftArray;
@property (strong, nonatomic) NSMutableDictionary *draftDictionary;
@end

@implementation TagViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tag_imageArray = [[NSArray alloc] init];
        self.tagArray = [[NSMutableArray alloc] init];
        self.tag_textArray = [[NSMutableArray alloc] init];
        self.tag_personArray = [[NSMutableArray alloc] init];
        self.tag_uploadImageArray = [[NSMutableArray alloc] init];
        self.allInfo = [[NSMutableDictionary alloc] init];
        self.attachment = [[NSMutableDictionary alloc] init];
        self.tag_audioWaveform = [[NSArray alloc] init];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getTagArray:) name:@"tagArray" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getPersonArrayFromAddPerson:) name:@"addPerson" object:nil];
    }
    return self;
}

- (void)getTagArray:(NSNotification *)notification{
    [_tagArray removeAllObjects];
    NSArray *tags = notification.object;
    [_tagArray addObjectsFromArray:tags];
    NSString *tagsStr = [_tagArray componentsJoinedByString:@","];
    _tagContent.text = tagsStr;
}
- (void)getPersonArrayFromAddPerson:(NSNotification *)notification {
    NSArray *array = notification.object;
    [_tag_personArray removeAllObjects];
    [_tag_personArray addObjectsFromArray:array];
}
- (void)getimageArray:(NSArray *)imageArray audioSecond:(NSNumber *)audioSecond waveArray:(NSArray *)waveArray text:(NSArray *)text person:(NSArray *)person workTime:(NSString *)workTime
{
    _tag_imageArray = imageArray;
    for (NSDictionary *dic in text) {
        NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *JsonDic = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [_tag_textArray addObject:JsonDic];
    }
    if (person != nil) {
        for (NSDictionary *dic in person) {
            NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
            NSString *JsonDic = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            [_tag_personArray addObject:JsonDic];
        }
    }
    self.tag_audioSecond = audioSecond;
    self.tag_audioWaveform = waveArray;
    self.tag_workTime = workTime;
    self.tag_imageNameArray = [NSMutableArray array];
    self.tag_imagePathArray = [NSMutableArray array];
}
- (void)findDraftFile{
    NSFileManager *managr = [NSFileManager defaultManager];
    NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [directoryPaths lastObject];
    self.draftPath = [documentDirectory stringByAppendingPathComponent:@"draft"];
    if ([managr fileExistsAtPath:_draftPath]) {
        self.draftArray = [NSMutableArray arrayWithContentsOfFile:_draftPath];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发布";
    self.view.backgroundColor = [UIColor whiteColor];
    self.hidesBottomBarWhenPushed = YES;
    price = 0.0f;
    // Do any additional setup after loading the view.
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"close"] style:UIBarButtonItemStylePlain target:self action:@selector(backAndSend)];
    backItem.tintColor = [UIColor blackColor];
    self.navigationItem.leftBarButtonItem = backItem;
    self.addTagController = [[AddTagViewController alloc] initWithTitle:@"标签"];
    [self createPublishButton];
    [self createViews];
    
    //定位管理器
    _locationManager=[[CLLocationManager alloc]init];
    if (![CLLocationManager locationServicesEnabled]) {
//        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        return;
    }
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        if (IOS8) {
            [_locationManager requestWhenInUseAuthorization];
        }
    }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
        //设置代理
        _locationManager.delegate=self;
        //设置定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        //定位频率,每隔多少米定位一次
        CLLocationDistance distance=10.0;//十米定位一次
        _locationManager.distanceFilter=distance;
        //启动跟踪定位
        [_locationManager startUpdatingLocation];
//        float latitude = 30;
//        float longitude = 120;  //这里可以是任意的经纬度值
//        CLLocation *location= [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
//        [[_locationManager delegate] locationManager:_locationManager didUpdateLocations:[NSArray arrayWithObject:location]];
    }
}

#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations lastObject];//取出第一个位置
    coordinate = location.coordinate;//位置坐标
//    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //根据经纬度反向地理编译出地址信息
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *array, NSError *error)
     {
//         NSLog(@"%@",array);
         if (array.count > 0)
         {
             placemark = [array objectAtIndex:0];

             if (_locationLabel) {
                 NSString *locationStr = [[NSString stringWithFormat:@"%@，%@，%@", placemark.locality, placemark.subLocality, placemark.thoroughfare] stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
                 if ([[locationStr substringFromIndex:locationStr.length - 1] isEqualToString:@"，"]) {
                     locationStr = [locationStr substringWithRange:NSMakeRange(0, locationStr.length - 1)];;
                 }
                 _locationLabel.text = locationStr;//[locationStr stringByReplacingOccurrencesOfString:@"(null)" withString:@""];//[NSString stringWithFormat:@"%@，%@，%@%@", placemark.locality, placemark.subLocality, placemark.thoroughfare,placemark.subThoroughfare];
//                 }
             }
         }
     }];
    //如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
}
- (void)backAndSend
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 
#pragma mark 判断图片色调
-(BOOL) isLightColor:(UIColor*)clr {
    CGFloat components[3];
    [self getRGBComponents:components forColor:clr];
//    NSLog(@"%f %f %f", components[0], components[1], components[2]);
    
    CGFloat num = components[0] + components[1] + components[2];
    if(num < 382)
        return NO;
    else
        return YES;
}
//获取RGB值
- (void)getRGBComponents:(CGFloat [3])components forColor:(UIColor *)color {
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char resultingPixel[4];
    CGContextRef context = CGBitmapContextCreate(&resultingPixel,
                                                 1,
                                                 1,
                                                 8,
                                                 4,
                                                 rgbColorSpace,
                                                 bitmapInfo);
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
    CGContextRelease(context);
    CGColorSpaceRelease(rgbColorSpace);
    
    for (int component = 0; component < 3; component++) {
        components[component] = resultingPixel[component];
    }
}
#pragma mark -
- (void)createViews
{
    UIColor *imageColor = nil;
    UIImage *firstImage = (UIImage *)[[_tag_imageArray firstObject] valueForKey:@"image"];
    imageColor = [firstImage mostColor];
    BOOL useBlack;
    nameView *name = [[nameView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height * 0.176)];
    name.imageView.image = firstImage;
    [self.view addSubview:name];
    
    if ([self isLightColor:imageColor]) {
        useBlack = YES;
    } else {
        useBlack = NO;
    }
    
    self.nameText = [[UITextField alloc] initWithFrame:CGRectMake(10, name.frame.size.height / 2 - 20, self.view.frame.size.width - 20, 35)];
    _nameText.delegate = self;
    _nameText.backgroundColor = [UIColor clearColor];
    _nameText.borderStyle = UITextBorderStyleNone;
    
    _nameText.textAlignment = NSTextAlignmentCenter;
    _nameText.font = [UIFont fontWithName:@"Arial" size:17];
    _nameText.returnKeyType = UIReturnKeyDone;
    _nameText.placeholder = @"添加作品名称";
    if (useBlack == NO) {
        [_nameText setValue:[UIColor colorWithWhite:0.652 alpha:1.000] forKeyPath:@"_placeholderLabel.textColor"];
        _nameText.textColor = [UIColor whiteColor];
    } else {

    }
    _nameText.returnKeyType = UIReturnKeyDone;
    [_nameText addTarget:self action:@selector(textFieldDidEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_nameText];
//    [_nameText becomeFirstResponder];
//位置信息
    self.locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, name.bounds.size.height - 20, self.view.bounds.size.width - 30, 15)];
    _locationLabel.font = [UIFont systemFontOfSize:10];

    if (useBlack == YES) {
        _locationLabel.textColor = [UIColor blackColor];
    } else {
        _locationLabel.textColor = [UIColor whiteColor];
    }
    if (placemark.locality) {
        _locationLabel.text = [NSString stringWithFormat:@"%@,%@,%@", placemark.locality, placemark.subLocality, placemark.thoroughfare];
    }
    [self.view addSubview:_locationLabel];
//标注人

    UIButton *person = [UIButton buttonWithType:UIButtonTypeCustom];
    person.frame = CGRectMake(0, name.frame.size.height, self.view.frame.size.width, name.frame.size.height * 0.4);
//    [person addTarget:self action:@selector(addPeople:)
//     forControlEvents:UIControlEventTouchUpInside];
    person.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:person];

    UIImageView *personImage = [[UIImageView alloc] initWithFrame:CGRectMake(15 , (person.frame.size.height - name.frame.size.height * 0.3) / 2 , name.frame.size.height * 0.3, name.frame.size.height * 0.3)];
    personImage.image = [UIImage imageNamed:@"tag_money"];
    [person addSubview:personImage];
    
    UILabel *personTitle = [[UILabel alloc] initWithFrame:CGRectMake(personImage.frame.size.width + personImage.frame.origin.x + 10, personImage.frame.origin.y, 80, personImage.frame.size.height)];
    personTitle.text = @"打赏";
    personTitle.font = [UIFont systemFontOfSize:17];
    personTitle.textColor = [UIColor blackColor];
    [person addSubview:personTitle];
    
    PKYStepper *stepper = [[PKYStepper alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 160, 7, 140, person.frame.size.height - 14)];
    stepper.maximum = 9.0f;
    stepper.countLabel.textColor = [UIColor blackColor];
    stepper.buttonWidth = stepper.frame.size.height;
    [stepper setBorderColor:[UIColor blackColor]];
    [stepper setBorderWidth:1.5];
    [stepper setButtonTextColor:[UIColor blackColor] forState:UIControlStateNormal];
    stepper.valueChangedCallback = ^(PKYStepper *stepper, float count) {
        if (count == 0) {
            stepper.countLabel.text = @"无";
        } else {
            stepper.countLabel.text = [NSString stringWithFormat:@"¥ %@", @(count)];
        }
        price = count;
    };
    [stepper setup];
    [person addSubview:stepper];
    
    UIImageView *personArrow = [[UIImageView alloc] initWithFrame:CGRectMake(person.frame.size.width - 15 - personImage.frame.size.width, personImage.frame.origin.y, personImage.frame.size.width, personImage.frame.size.height)];
    personArrow.image = [UIImage imageNamed:@"tag_nextButton"];
//    [person addSubview:personArrow];
    
//标签
    self.addTag = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addTag setFrame:CGRectMake(0, person.frame.origin.y + person.frame.size.height, person.frame.size.width, person.frame.size.height)];
    _addTag.backgroundColor = [UIColor whiteColor];
    [_addTag addTarget:self action:@selector(addTag:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_addTag];
    
    UIImageView *tagImage = [[UIImageView alloc] initWithFrame:CGRectMake(15, (_addTag.frame.size.height - name.frame.size.height * 0.3) / 2 , name.frame.size.height * 0.3, name.frame.size.height * 0.3)];
    tagImage.image = [UIImage imageNamed:@"tag_addTag"];
    [_addTag addSubview:tagImage];
    
    UILabel *tagLabel = [[UILabel alloc] initWithFrame:CGRectMake(tagImage.frame.origin.x + tagImage.frame.size.width + 10, tagImage.frame.origin.y, 80, tagImage.frame.size.height)];
    tagLabel.text = @"添加标签";
    tagLabel.font = [UIFont systemFontOfSize:17];
    tagLabel.textColor = [UIColor blackColor];
    [_addTag addSubview:tagLabel];
    
    self.tagContent = [[UILabel alloc] initWithFrame:CGRectMake(_addTag.frame.size.width - 15 - tagImage.frame.size.width - 100, tagLabel.frame.origin.y, 100, tagLabel.frame.size.height)];
    _tagContent.font = [UIFont systemFontOfSize:17];
    _tagContent.textColor = [UIColor colorWithWhite:0.594 alpha:1.000];
    _tagContent.textAlignment = NSTextAlignmentRight;
    [_addTag addSubview:_tagContent];
    
    UIImageView *tagArrow = [[UIImageView alloc] initWithFrame:CGRectMake(_addTag.frame.size.width - 15 - tagImage.frame.size.width, tagImage.frame.origin.y, tagImage.frame.size.width, tagImage.frame.size.height)];
    tagArrow.image = [UIImage imageNamed:@"tag_nextButton"];
    [_addTag addSubview:tagArrow];
    
    
//仅自己
    UIButton *onlySelf = [[UIButton alloc] initWithFrame:CGRectMake(0, _addTag.frame.origin.y + _addTag.frame.size.height, self.view.frame.size.width, person.frame.size.height)];
    onlySelf.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:onlySelf];
    
    UIImageView *onlySelfImage = [[UIImageView alloc] initWithFrame:CGRectMake(15, (onlySelf.frame.size.height - name.frame.size.height * 0.3) / 2, name.frame.size.height * 0.3, name.frame.size.height * 0.3)];
    onlySelfImage.image = [UIImage imageNamed:@"tag_onlySelf"];
    [onlySelf addSubview:onlySelfImage];
    
    UILabel *onlySelfLabel = [[UILabel alloc] initWithFrame:CGRectMake(onlySelfImage.frame.size.width + onlySelfImage.frame.origin.x + 10, onlySelfImage.frame.origin.y, 110, onlySelfImage.frame.size.height)];
    onlySelfLabel.text = @"仅自己可见";
    onlySelfLabel.font = [UIFont systemFontOfSize:17];
    onlySelfLabel.textColor = [UIColor blackColor];
    [onlySelf addSubview:onlySelfLabel];
    
    self.Private = [[UISwitch alloc] initWithFrame:CGRectMake(self.view.frame.size.width *0.766, onlySelfLabel.frame.origin.y, 2*self.view.frame.size.width * 0.3, self.view.frame.size.width * 0.3)];
    _Private.frame = CGRectMake(self.view.width - 20 - _Private.width, _Private.top, _Private.width, _Private.height);
    _Private.on = 0;
     [AppDelegate shareDelegate].onlySelf = [NSNumber numberWithBool:NO];
    [_Private addTarget:self action:@selector(OpenOrClose:) forControlEvents:UIControlEventValueChanged];
    [onlySelf addSubview:_Private];
    
    UIButton *wexinBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, onlySelf.frame.origin.y + onlySelf.frame.size.height, self.view.frame.size.width, person.frame.size.height)];
    onlySelf.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:wexinBtn];
    
    UIImageView *weixinImage = [[UIImageView alloc] initWithFrame:CGRectMake(15, (onlySelf.frame.size.height - name.frame.size.height * 0.3) / 2, name.frame.size.height * 0.3, name.frame.size.height * 0.3)];
    weixinImage.image = [UIImage imageNamed:@"iconfont-pengyouquan"];
    [wexinBtn addSubview:weixinImage];
    
    UILabel *weixinLabel = [[UILabel alloc] initWithFrame:CGRectMake(onlySelfImage.frame.size.width + onlySelfImage.frame.origin.x + 10, onlySelfImage.frame.origin.y, 110, onlySelfImage.frame.size.height)];
    weixinLabel.text = @"分享到朋友圈";
    weixinLabel.font = [UIFont systemFontOfSize:17];
    weixinLabel.textColor = [UIColor blackColor];
    [wexinBtn addSubview:weixinLabel];
    
    self.weixinSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(_Private.left, onlySelfLabel.frame.origin.y, 2*name.frame.size.width * 0.3, name.frame.size.width * 0.3)];
    _weixinSwitch.on = 1;
    [_weixinSwitch addTarget:self action:@selector(weixinOpenOrClose:) forControlEvents:UIControlEventValueChanged];
    [wexinBtn addSubview:_weixinSwitch];
    [AppDelegate shareDelegate].weixinShare = [NSNumber numberWithBool:YES];
//显示位置信息
    UIView *locationView = [[UIView alloc] initWithFrame:CGRectMake(0, wexinBtn.frame.origin.y + wexinBtn.frame.size.height, self.view.frame.size.width, person.frame.size.height)];
    locationView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:locationView];
    
    UIImageView *locationImage = [[UIImageView alloc] initWithFrame:CGRectMake(15 , (person.frame.size.height - name.frame.size.height * 0.3) / 2 , name.frame.size.height * 0.3, name.frame.size.height * 0.3)];
    locationImage.image = [UIImage imageNamed:@"iconfont-dingwei"];
    [locationView addSubview:locationImage];
    
    UILabel *locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(onlySelfImage.frame.size.width + onlySelfImage.frame.origin.x + 10, onlySelfImage.frame.origin.y, 110, onlySelfImage.frame.size.height)];
    locationLabel.text = @"显示位置信息";
    locationLabel.font = [UIFont systemFontOfSize:17];
    locationLabel.textColor = [UIColor blackColor];
    [locationView addSubview:locationLabel];
    
    UISwitch *locationSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(_Private.left, onlySelfLabel.frame.origin.y, 2*name.frame.size.width * 0.3, name.frame.size.width * 0.3)];
    locationSwitch.on = 1;
    [locationSwitch addTarget:self action:@selector(locationOpenOrClose:) forControlEvents:UIControlEventValueChanged];
    [locationView addSubview:locationSwitch];
}
#pragma mark -
#pragma mark textfield 协议
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.name = textField.text;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length > 25) {
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"作品名称不能超过20个字符" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];
        textField.text = [textField.text substringToIndex:25];
        return NO;
    } else {
        [textField resignFirstResponder];
        return YES;
    }
}
- (void)textFieldDidEditingChanged:(UITextField *)textField
{
    
//    [textField.text enumerateSubstringsInRange:NSMakeRange(0, [textField.text length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
//        const unichar hs = [substring characterAtIndex:0];
//        if (0xd800 <= hs && hs <= 0xdbff) {
//            if (substring.length > 1) {
//                const unichar ls = [substring characterAtIndex:1];
//                const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
//                if (0x1d000 <= uc && uc <= 0x1f77f) {
//                    [textField deleteBackward];
//                }
//            }
//        } else if (substring.length > 1) {
//            const unichar ls = [substring characterAtIndex:1];
//            if (ls == 0x20e3) {
//                [textField deleteBackward];
//            }
//        } else {
//            if (0x2100 <= hs && hs <= 0x27ff) {
//                [textField deleteBackward];
//            } else if (0x2B05 <= hs && hs <= 0x2b07) {
//                [textField deleteBackward];
//            } else if (0x2934 <= hs && hs <= 0x2935) {
//                [textField deleteBackward];
//            } else if (0x3297 <= hs && hs <= 0x3299) {
//                [textField deleteBackward];
//            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
//                [textField deleteBackward];
//            }
//        }
//    }];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
        return YES;
    } else {
        return YES;
    }
}
- (void)addPeople:(UIButton *)sender{
    UIImage *viewImage = [UIImage imageNamed:@"addperson_background"];
    AddPersonViewController *addPerson = [[AddPersonViewController alloc] init];
    [addPerson getWindowImg:viewImage personArray:_tag_personArray];
    [self.navigationController pushViewController:addPerson animated:YES];
}


#pragma mark -
#pragma mark 标签按钮点击事件
- (void)addTag:(UIButton *)sender
{
    [self.navigationController pushViewController:_addTagController animated:YES];
}
#pragma mark -
#pragma mark 是否公开 开关

- (void)OpenOrClose:(UISwitch *)Switch
{
    if (Switch.on == YES) {
        self.isPrivate = YES;
        [AppDelegate shareDelegate].onlySelf = [NSNumber numberWithBool:YES];
        [_weixinSwitch setOn:NO animated:YES];
        [AppDelegate shareDelegate].weixinShare = [NSNumber numberWithBool:NO];
    } else {
        self.isPrivate  = NO;
         [AppDelegate shareDelegate].onlySelf = [NSNumber numberWithBool:NO];
        [_weixinSwitch setOn:YES animated:YES];
        [AppDelegate shareDelegate].weixinShare = [NSNumber numberWithBool:YES];
    }
}
- (void)weixinOpenOrClose:(UISwitch *)Switch
{
    if (Switch.on == YES) {
        [AppDelegate shareDelegate].weixinShare = [NSNumber numberWithBool:YES];
    } else {
        [AppDelegate shareDelegate].weixinShare = [NSNumber numberWithBool:NO];
    }
}
- (void)locationOpenOrClose:(UISwitch *)Switch
{
    if (Switch.on == YES) {
        _locationLabel.hidden = NO;
    } else {
        _locationLabel.hidden = YES;
    }
}
#pragma mark -
#pragma mark 创建发布按钮
- (void)createPublishButton{
    UIBarButtonItem *publishItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"upload"] style:UIBarButtonItemStylePlain target:self action:@selector(publish:)];
    publishItem.tintColor = [UIColor blackColor];
    self.navigationItem.rightBarButtonItem = publishItem;
}
- (void)publish:(UIButton *)sender{
    [_nameText resignFirstResponder];
    if (_nameText.text.length > 0) {
        _name = _nameText.text;
        if (price == 0.0) {
            [self sureWithPublish];
        } else {
            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"SoundLab将收取10%手续费，用于支付第三方平台费用\n用户每周可提现一次，每次提现大于100元免提现费2元" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                [self sureWithPublish];
            }];
        }
    } else {
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"请输入作品名" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
            
        }];
    }
}
- (void)sureWithPublish
{
    dispatch_async(dispatch_queue_create(0, 0), ^{
        NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *DouNiu = [strUrl stringByAppendingPathComponent:@"DouNiu"];
        NSString *Draftwork = [DouNiu stringByAppendingPathComponent:_tag_workTime];
        NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:Draftwork error:nil];
        for (NSString *fileName in fileList) {
            if ([fileName rangeOfString:@"full"].location != NSNotFound) {
                NSString *fullPath = [Draftwork stringByAppendingPathComponent:fileName];
                [_tag_imageNameArray addObject:fileName];
                [_tag_imagePathArray addObject:fullPath];
            }
        }
        UploadWork *upload = [[UploadWork alloc] initWithWorkTime:_tag_workTime workSpace:Draftwork tag_imageNameArray:_tag_imageNameArray tag_imagePathArray:_tag_imagePathArray tag_uploadImageArray:_tag_uploadImageArray tag_imageArray:_tag_imageArray workname:_name audioSecond:_tag_audioSecond Private:[NSNumber numberWithBool:_isPrivate]];
        upload.tag_textArray = _tag_textArray;
        upload.tagArray = _tagArray;
        upload.tag_personArray = _tag_personArray;
        upload.priceNum = [NSNumber numberWithFloat:price];
        if (_locationLabel.hidden == NO) {
            upload.coordinate = coordinate;
            upload.location = _locationLabel.text;
        }
        [upload UpLoad:[Draftwork stringByAppendingFormat:@"/%@.mp3", _tag_workTime] wavePath:[Draftwork stringByAppendingPathComponent:@"waveform.json"]];
        
    });
    
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    MMDrawerController *draw = (MMDrawerController *)[AppDelegate shareDelegate].window.rootViewController;
    UITabBarController *tab = (UITabBarController *)draw.centerViewController;
    tab.selectedIndex = 4;
    [self dismissViewControllerAnimated:YES completion:^{
        [AppDelegate shareDelegate].playerStateBtn.hidden = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"uploadState" object:@"upload"];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
